package com.jiliason.testTools;

import com.google.common.collect.Lists;
import com.jiliason.testTools.constant.TCt;
import com.jiliason.testTools.entity.TestDataPojo;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

@Component
public class PackageTestDataLoad implements TestDataLoader {

    protected final String testDocRoot = TCt.testDocRootPath;

    @Override
    public <T> List<TestDataPojo> loadTestData(T t) {
        return Lists.newArrayList();
    }

    @Override
    public List<TestDataPojo> loadTestData() throws Exception {
        List<TestDataPojo> res = load(TCt.packageTag);
        return Collections.unmodifiableList(res);
    }

    public List<TestDataPojo> load(String tag) throws Exception {
        PathMatchingResourcePatternResolver s = new PathMatchingResourcePatternResolver();

        List<org.springframework.core.io.Resource> l = Arrays.stream(s.getResources(ResourceUtils.FILE_URL_PREFIX + testDocRoot))
                .filter(org.springframework.core.io.Resource::isFile)
                .filter(r -> Objects.requireNonNull(r.getFilename()).startsWith(tag))
                .toList();

        List<TestDataPojo> res = Lists.newArrayList();

        for (org.springframework.core.io.Resource r : l) {
            List<TestDataPojo> temp = InitTestData.getTestDataByPath(r.getFile().toPath());
            res.addAll(temp);
        }

        return Collections.unmodifiableList(res);
    }
}
